(() => {
    const layer = document.querySelector('#words').children[0]
    const inputLayer = document.querySelector('#inputfield')
    const gameTimer = document.querySelector('#timer')
    const eventManager = new EventTarget()
    let typeSpeed = 0.3 // 打字速度 秒 / 字
    let targetData = []
    let index = 0
    let isGameOver = false

    // 收集单词列表
    const collectTarget = () => {
        let c = layer.children
        for (let i = 0; i < c.length; i++) {
            let td = c[i].innerText
            targetData.push(td)
        }
        console.log('collect done')
        inputNext()
    }

    // 输入下一个单词
    const inputNext = () => {
        if (index < targetData.length) {
            const targetStr = targetData[index]
            inputLayer.value = targetStr
            // console.log(targetStr)
            index++
            checkIsOver()

            eventManager.dispatchEvent(new Event('refreshMsg'))

            if (!isGameOver) { // 如果游戏没结束就输入空格，然后输入下个单词
                setTimeout(() => {
                    inputLayer.dispatchEvent(new KeyboardEvent('keyup', { 'keyCode': 32, 'which': 32 }))
                    inputNext()
                }, typeSpeed * 1000)
            }

        }
    }

    // 检查游戏是否结束
    const checkIsOver = () => {
        if (gameTimer.innerText == '0:00') {
            isGameOver = true
        }
    }

    const createLayer = () => {
        const layer = document.createElement('div')
        layer.style = 'display: block; padding: 0px; margin: 0px; z-index: 999; position: fixed; top:0; left: 0; background-color:rgba(255,255,255,0.8);'
        document.body.appendChild(layer)
        return layer
    }

    const createReplayButton = (layer) => {
        const btn = document.createElement('button')
        btn.innerText = '重新开始'
        btn.style = 'margin: 3px;font-size: 10px;'
        layer.appendChild(btn)
        btn.onclick = replay
    }

    const createMessageLog = (layer) => {
        const prg = document.createElement('p')
        prg.innerText = '当前打字速度 ' + typeSpeed + ' 秒/词\n'
        prg.style = 'margin: 3px;font-size: 10px;line-height:15px'
        prg.id = 'message-log-prg'
        layer.appendChild(prg)
    }

    const createPanel = () => {
        let layer = createLayer()
        createReplayButton(layer)
        createMessageLog(layer)
    }

    // 重新开始
    const replay = () => {
        targetData = []
        index = 0
        isGameOver = false
        collectTarget()
    }

    const refreshMessageLog = () => {
        try {
            const prg = document.getElementById('message-log-prg')
            let str = '当前打字速度 ' + typeSpeed + ' 秒/词\n'
            str += '\n下一个输入的词 ' + targetData[index]
            prg.innerText = str
        } catch (e) {

        }

    }

    // 事件初始化
    const eventListenerInit = () => {
        eventManager.addEventListener('refreshMsg', refreshMessageLog)
    }

    createPanel()
    eventListenerInit()
    collectTarget()
})()
